<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<style>
		div {
			width: 500px;
			height: 300px;
			background-color: pink;
			margin: 50px auto 0;
		}
	</style>
	<script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
</head>

<body>
	<!-- 防抖和节流都是性能优化的一种手段 -->
	<!-- 防抖：持续触发不执行，不触发的一段时间后才执行 -->
	<!-- 节流：持续触发也执行，只不过执行的频率变低了 -->
	<!-- 实现一个防抖和节流 -->
	<!-- 不过一般呀，我在实际开发当中更喜欢用 lodash 里面的防抖函数 -->
	<!-- 应用场景：防抖（根据输入内容发请求）节流（滚动的时候获取位置） -->
	<!-- 生活场景：防抖（王者荣耀英雄回城）节流（CS 里面散弹枪） -->
	<div id="oDiv"></div>
	<script>
		// 需求：鼠标滑过 div 实时获取鼠标相对于盒子的位置，并展示出来
		/* oDiv.onmousemove = function (e) {
			const x = arguments[0].pageX - this.offsetLeft;
			const y = e.pageY - this.offsetTop
			this.innerHTML = `x ${x},y ${y}`
		}; */
		/* let timer = null
		oDiv.onmousemove = function (e) {
			clearTimeout(timer)
			timer = setTimeout(() => {
				const x = e.pageX - this.offsetLeft;
				const y = e.pageY - this.offsetTop
				this.innerHTML = `x ${x},y ${y}`
			}, 100)
		}; */
		// 封装一个防抖函数
		/* const debounce = (callback, time) => {
			// 返回值 => 类型？
			let timer = null
			return function (e) {
				// this => oDiv
				clearTimeout(timer)
				timer = setTimeout(() => {
					callback.call(this, e) // window.callback()
				}, time)
			}
		}
		oDiv.onmousemove = debounce(function (e) {
			// this => oDiv
			const x = e.pageX - this.offsetLeft;
			const y = e.pageY - this.offsetTop
			this.innerHTML = `x ${x},y ${y}`
		}, 20); */
		/* const debounce = (callback, time) => {
			let timer = null
			return function (e) {
				clearTimeout(timer)
				timer = setTimeout(() => {
					callback.apply(this, arguments)
				}, time)
			}
		}
		oDiv.onmousemove = debounce(function (e) {
			// this => oDiv
			const x = e.pageX - this.offsetLeft;
			const y = e.pageY - this.offsetTop
			this.innerHTML = `x ${x},y ${y}`
		}, 20); */
		/* const debounce = (callback, time) => {
			let timer = null
			return function (e) {
				clearTimeout(timer)
				timer = setTimeout(() => {
					callback.apply(this, arguments)
				}, time)
			}
		} */
		oDiv.onmousemove = _.debounce(function (e) {
			// this => oDiv
			const x = e.pageX - this.offsetLeft;
			const y = e.pageY - this.offsetTop
			this.innerHTML = `x ${x},y ${y}`
		}, 50);
	</script>
</body>

</html>